package com.foreknow.elm.framework;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 自定义前端控制器 拦截url格式要求： /控制器类名/控制器方法名
 * 核心控制器
 * 作用: 通过反射动态调用Controller中的方法。最终将结果返回给客户端
 *  http://localhost:8080/elm/Controller类名/Controller方法名
 */
@WebServlet("/")
public class DispatcherServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置从后台向前台返回的内容类型(数据格式为JSON)
        resp.setContentType("application/json;charset=utf-8");
        //设置请求的字符编码集
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        //获取客户端请求路径
        String path = req.getServletPath(); //    /test/abc
        //类名
        String className = path.substring(1,path.lastIndexOf("/"));
        //方法名
        String methodName = path.substring(path.lastIndexOf("/") + 1);
        //通过反射调用Controller中的方法
        try {
            //获取类
            Class clazz = Class.forName("com.foreknow.elm.controller." + className);
            //创建对象
            Object controller = clazz.newInstance();
            //获取方法
            Method method = clazz.getMethod(methodName,HttpServletRequest.class);
            //调用方法
            Object result = method.invoke(controller,req);
            //要将结果以JSON的数据格式返回给前台
            ObjectMapper mapper = new ObjectMapper();
            out.println(mapper.writeValueAsString(result));

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println(path);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
